package com.haidechizi.fastadmin.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 获取request以及语言的工具类
 */
public class RequestUtils {

    public static String getLocale(String key) {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        return getLocale(request, key);
    }


    public static String getLocale(HttpServletRequest request, String key) {
        String value = getHeaderValue(request, key);
        if (StringUtils.isNotBlank(value)) {
            return value;
        }
        return getCookieValue(request, key);
    }

    public static String getZone(String key) {
        HttpServletRequest request = getRequest();
        return getZone(request, key);
    }

    public static String getZone(HttpServletRequest request, String key) {
        String value = getHeaderValue(request, key);
        if (StringUtils.isNotBlank(value)) {
            return value;
        }
        return getCookieValue(request, key);
    }

    public static String getTranslate(String key) {
        HttpServletRequest request = getRequest();
        return getTranslate(request, key);
    }

    public static String getTranslate(HttpServletRequest request, String key) {
        String value = getHeaderValue(request, key);
        if (StringUtils.isNotBlank(value)) {
            return value;
        }
        return getCookieValue(request, key);
    }

    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        if (request == null) {
            return null;
        }
        return request;
    }


    public static String getCookieValue(HttpServletRequest request, String key) {
        if (request == null) {
            return null;
        }
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null) {
            return null;
        }
        String cookieValue = null;

        for (int i = 0; i < cookieList.length; i++) {
            if (cookieList[i].getName().equals(key)) {
                cookieValue = cookieList[i].getValue();
                break;
            }
        }
        return cookieValue;
    }

    public static String getHeaderValue(HttpServletRequest request, String key) {
        if (request == null) {
            return null;
        }
        return request.getHeader(key);
    }
}
